package com.buddy.zookeeper.client;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.Date;

public class AdminClient implements Watcher {

    ZooKeeper zk;String hostPort;
    AdminClient(String hostPort){
        this.hostPort = hostPort;
    }
    void start() throws IOException {
        zk = new ZooKeeper(hostPort,15000,this);
    }

    void listState() throws KeeperException, InterruptedException {
        try {
            Stat stat = new Stat();
            byte[] masterData = zk.getData("/master",false,stat);
            String data = new String(masterData);
            Date startDate = new Date(stat.getCtime());
            System.out.println("----->"+data+" since "+startDate);
        } catch (KeeperException.NoNodeException e) {
            e.printStackTrace();
        }catch (KeeperException.ConnectionLossException e){

        }

        for (String w:zk.getChildren("/workers",false)){
            byte[] data = zk.getData("/workers/"+w,false,null);
            String state = new String(data);
            System.out.println("---------->"+w+":"+state);
        }
    }

    public void process(WatchedEvent event) {
        System.out.println(event);
    }

    public void close() throws InterruptedException {
        zk.close();
    }

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        AdminClient c = new AdminClient("127.0.0.1:2181");
        c.start();
        c.listState();
        c.close();
    }
}
